package org.mc.sbd.mqredis.config;

import lombok.Data;
import org.mc.sbd.mqredis.event.MqEvent;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.Map;

@Data
@Configuration
//@ConditionalOnProperty(prefix = "redis-mq", name = "event-mapping")
@ConfigurationProperties(prefix = "redis-mq")
public class RedisMqConfig implements ApplicationContextAware {
    //    @Value("${redis-mq.event-mapping:#{null}}")
    private Map<RedisMqMappingEnum, String> eventMapping;

    private static ApplicationContext applicationContext;

    @Bean
    public RedisTemplate<String, MqEvent> eventRedisClient(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, MqEvent> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
        return template;
    }

    @Bean
    public RedisMessageListenerContainer messageListenerContainer(RedisConnectionFactory connectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);

        eventMapping.forEach((key, value) -> {
            container.addMessageListener((MessageListener) applicationContext.getBean(value), new PatternTopic(key.toString()));
        });

        return container;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        if (RedisMqConfig.applicationContext == null) {
            RedisMqConfig.applicationContext = applicationContext;
        }
    }
}